from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Carousel
from .serializer import CarouselSer,GoodSer,GoodImgSer,GoodCategorySer
from .models import GoodCategory,Good,GoodImg
from functools import reduce
import jwt,redis
from django.conf import settings
from django.core.paginator import Paginator

# Create your views here.

# 轮播图视图类
class CarouselAPIView(APIView):

    def get(self,request):
        # 查询所有的轮播图数据，返回给前端
        # 轮播图的模型类
        carousels_queryset = Carousel.objects.all()
        carousels_queryset_ser = CarouselSer(carousels_queryset,many=True)

        return Response({"code":200,"msg":"获取轮播图成功",
                         "carousel":carousels_queryset_ser.data})

# 加载一个类的商品数据
class OneCategoryGoods(APIView):
    def get(self,request):
        # 1.获取前端类别
        cate_name = request.query_params.get("categoryName")
        # 2.根据类别名  查询类别对象
        try:
            cate_obj = GoodCategory.objects.get(cate_name=cate_name)
        except:
            return Response({"code":204,'msg':'该类别不存在'})
        # 3.由类别对象 感想查询该类的所有商品
        goods_queryset = cate_obj.good_set.all()
        goods_queryset_set = GoodSer(goods_queryset, many=True)

        # 返回响应
        return Response(goods_queryset_set.data)

# 热门商品
class HotProduct(APIView):
    def get(self,request):
        # 1.获取商品类别
        # print("查看类别：", request.query_params)
        cate_list = request.query_params.getlist("categoryName[]")

        # 2.根据每一个类别名字，查询商品类别对象
        cate_obj_list = [GoodCategory.objects.get(cate_name=i) for i in cate_list]

        # 3.根据每一个类别对象，反向查询其对应的所有商品
        good_queryset_list = [i.good_set.all() for i in cate_obj_list]

        # 4.将所有的商品集合，进行 并的 操作
        # temp = set()
        # for i in good_queryset_list:
        #     temp |= i
        goods_queryset = reduce(lambda x,y: x|y, good_queryset_list)

        # 5.将所有商品进行序列化
        goods_queryset_set = GoodSer(goods_queryset, many=True)

        return Response(goods_queryset_set.data)


# 商品详情
class GoodDetail(APIView):
    def get(self,request):

        # 1.接收商品id
        good_id = request.query_params.get('productID')

        # 2.根据商品id 查询商品对象
        try:
            good = Good.objects.get(id=good_id)
        except:
            return Response({"code":204, 'msg':'商品不存在'})

        # 3.序列化
        good_ser = GoodSer(good)

        return Response(good_ser.data)


# 详情轮播图
class DetailCarousel(APIView):
    def get(self, request):
        # 1.获取前端数据,商品id
        good_id = request.query_params.get("productID")
        # 2.根据当前商品id 查询商品对象
        try:
            good = Good.objects.get(id = good_id)
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'商品不存在'})
        # 3.根据商品对象 反向查询其所有图片对象
        img_queryset = good.goodimg_set.all()

        # 4.对所有的图片对象,进行序列化
        img_queryset_ser = GoodImgSer(img_queryset, many=True)

        return Response(img_queryset_ser.data)


# 添加历史记录
class GoodHistory(APIView):
    def post(self,request):

        # 1.获取前端数据
        good_id = request.data.get("productID")
        token = request.data.get("token")

        # 2.根据token的值，做相应的操作
        if not token:   # 没有token
            return Response({"code":203, 'msg':'没有token'})

        # 3.有token，需要对token解码
        try:
            payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms='HS256')
        except Exception as e:
            print(e)
            return Response({"code":204, 'msg':'token解码错误'})

        # 4.解析出payload
        username = payload.get("username")

        # 构造key
        key = "history:%s" % username

        # 6.操作Redis 储存历史记录
        redis_conn = redis.Redis(host='localhost', port=6379, db=0, password='123')

        # 列表的删除、添加、截取
        redis_conn.lrem(key, 0, good_id)
        redis_conn.lpush(key, good_id)
        redis_conn.ltrim(key, 0, 4)

        redis_conn.close()

        return Response({'code':200, 'msg':'添加历史记录成功'}, status=201)



# 加载所有的商品类别
class CategoryAPIView(APIView):
    def get(self,request):
        # 1.查询所有的类别对象
        cate_queryset = GoodCategory.objects.all()
        # 2.序列化所有的类别对象
        cate_queryset_ser = GoodCategorySer(cate_queryset, many=True)

        # 3.返回相应
        return Response({"code":200, 'msg':'获取所有的商品类别成功', 'category':cate_queryset_ser.data})


# 加载所有的商品
class GoodAPIView(APIView):
    def get(self,request):

        # 1.接受当前数据, 便于实现所有商品的分页效果
        current_page = request.query_params.get("currentPage")
        page_size = request.query_params.get("pageSize")

        # 2.查询所有的商品对象
        goods_queryset = Good.objects.all()

        # 在第二步， 增加商品的分页实现
        paginator = Paginator(goods_queryset, page_size)
        # 获取当前页面对象
        page = paginator.page(current_page)

        # 3.序列化 当前页面的 所有的商品对象
        goods_queryset_ser = GoodSer(page.object_list, many=True)


        return Response({"code":200, 'msg':'加载所有商品成功',
                         "product":goods_queryset_ser.data,
                         "total":goods_queryset.count()})


# 加载指定类别的商品
class GoodByCategory(APIView):
    def get(self,request):
        # 1.接受前端数据
        care_id = request.query_params.get("categoryID[]")
        current_page = request.query_params.get("currentPage")
        page_size = request.query_params.get("pageSize")

        # 2.根据种类id 查询种类对象
        cate = GoodCategory.objects.get(id=care_id)

        # 3.通过种类对象， 反向查询该类的所有商品
        goods_queryset = cate.good_set.all()
        paginator = Paginator(goods_queryset, page_size)
        page = paginator.page(current_page)

        # 4.序列化所有商品对象
        goods_queryset_ser = GoodSer(page.object_list, many=True)

        return Response({"code":200, "msg":'获取指定类别的商品成功',
                         "product":goods_queryset_ser.data,
                         "total":goods_queryset.count()})




